﻿using System;
using System.Net;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Lifestyle;
using Castle.MicroKernel;
using Castle.MicroKernel.Context;

namespace Structura.Castle.Windsor.Lifecycle
{
	/// <summary>
	/// Summary description for SingletonLifestyleManager.
	/// </summary>
#if (!SILVERLIGHT)
	[Serializable]
#endif
	public class SingletonLifestyleManager : AbstractLifestyleManager
	{
		private volatile Object instance;

		public override void Init(IComponentActivator componentActivator, IKernel kernel, global::Castle.Core.ComponentModel model)
		{
			// replace the component activator with out custom one, this lifestyle ignores any custom activator we can
			// attach to the registered type
			AbstractComponentActivator aca = componentActivator as AbstractComponentActivator;
			componentActivator = new SingletonComponentActivator(model, kernel, aca.OnCreation, aca.OnDestruction);
         base.Init(componentActivator, kernel, model);
		}

		public override void Dispose()
		{
			if (instance != null) base.Release(instance);
		}

		public override object Resolve(CreationContext context)
		{
			if (instance == null)
			{
				lock (ComponentActivator)
				{
					if (instance == null)
					{
						// implementation 2
						instance = (ComponentActivator as SingletonComponentActivator).Create(context, ref instance);

						// implementation 1
						//instance = base.Resolve(context);
						//// we can now ask for propery resolution
						//(ComponentActivator as SingletonComponentActivator).SetUpProperties(instance, context);
					}
				}
			}

			return instance;
		}

		public override bool Release(object instance)
		{
			// Do nothing
			return false;
		}
	}
}
